var http = require('../../script/api.js');
var config = require('../../script/config.js');
import tool from '../../utils/common.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    submitData: {
      /******** 来电信息 ***********/
      UserSource: '',
      UserSourceName: '',
      CONS_NAME_1: '',
      PhoneNumber: '',
      ServiceType: '',
      ServiceTypeName: '',
      SubType: '',
      SubTypeName: '',
      /******** 来电信息 ***********/
      /******** 房屋信息 ***********/
      Meter_No: '',
      DeptNo: '',
      DeptName: '',
      buildingName: '',
      CONS_NAME: '',
      CONS_NAME_Search_1: '',
      CONS_NAME_Search_2: '',
      CONS_NO: '',
      CONS_NO_Search_1: '',
      CONS_NO_Search_2: '',
      Room: '',
      Unit: '',
      Address: '',
      Address_Search_1: '',
      Address_Search_2: '',
      /******** 房屋信息 ***********/
      /******** 工单信息 ***********/
      UrgencyID: "",
      UrgencyName: '',
      TimeLimit: '',
      TimeLimitName: '',
      AppointmentBeginTime: '',
      AppointmentEndTime: '',
      Description: '',
      /******** 工单信息 ***********/

      /******** 处理信息 ***********/
      HandlerResult: '',
      Status: '02',
      AssignDeptNo: '',
      HandleUserNo: '',
      ZpName: '',
      /******** 处理信息 ***********/
    },
    /******** 用户查询 ***********/
    SearchType: '1',
    DeptTree: [],
    DeptTreeShow: [],
    fieldNames: {
      text: 'NodeName',
      value: 'NodeCode',
      children: 'Children',
    },
    DeptShow: false,
    placeholder: '请选择',
    /******** 用户查询 ***********/

    /******** 基础数据 ***********/
    UserSourceTypeList: [],
    UserSourceActive: 0,
    UserSourceShow: false,
    ServiceTypeList: [],
    ServiceTypeActive: 0,
    ServiceTypeShow: false,
    SubTypeList: [],
    SubTypeActive: 0,
    SubTypeShow: false,
    UrgencyList: [],
    UrgencyActive: 0,
    UrgencyShow: false,
    TimeLimitList: [],
    TimeLimitActive: 0,
    TimeLimitShow: false,
    setNow: false,
    /******** 基础数据 ***********/

    /********** 转派树 *********/
    zpShow: false,
    dataTree: [],
    isSelectLastNode: true,
    DEPT_NO: '',
    AssignDeptNo: '',
    HandleUserNo: '',
    Select_DEPT_NAME: '',
    searchDeptTxt: '',
    /********** 转派树 *********/
    userinfo: null,
    WeatherInfo: null,
    sendInfo: null, // 兼容附件上传控件传递的数据
    NeedFile: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getUserInfo();
    this.GetPCodes();
    this.GetWorkOrderType();
    this.GetUrgency();
    this.GetDeptUserTree();
    this.GetSysDeptTree();
    this.GetCurrentWeather();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  getUserInfo: function () {
    try {
      var value = wx.getStorageSync(config.storageKey.userinfo)
      if (value) {
        this.setData({
          userinfo: value
        });
      }
    } catch (e) {}
  },
  GetPCodes() {
    http.GetPCodes({
      keys: ['UserSourceType', 'OrderTimeLimit'],
    }).then(res => {
      const TimeLimit = [...res.data.OrderTimeLimit];
      TimeLimit.sort((a, b) => parseInt(a.name) - parseInt(b.name));
      TimeLimit.map(item => {
        item.showName = item.name + '小时'
      })
      this.setData({
        UserSourceTypeList: res.data.UserSourceType,
        TimeLimitList: TimeLimit,
        "submitData.TimeLimit": TimeLimit[0].value,
        "submitData.TimeLimitName": TimeLimit[0].showName,
      })
    })
  },
  GetWorkOrderType() {
    http.GetWorkOrderType({
      keys: ['UserSourceType'],
    }).then(res => {
      if (res.code === 200) {
        this.setData({
          ServiceTypeList: res.data && res.data.length > 0 ? res.data[0].ChildNodeList : []
        })
      }
    })
  },
  GetUrgency() {
    http.GetUrgency().then(res => {
      if (res.code === 200) {
        this.setData({
          UrgencyList: res.data,
          "submitData.UrgencyID": res.data[0].UrgencyID,
          "submitData.UrgencyName": res.data[0].UrgencyName,
        })
      }
    })
  },
  GetDeptUserTree() {
    http.GetDeptUserTree({}).then(res => {
      if (res.code === 200) {
        this.setData({
          dataTree: res.data[0].MODELLIST,
        })
      }
    })
  },
  GetSysDeptTree() {
    http.GetSysDeptTree({
      NodeType: '2,4'
    }).then(res => {
      if (res.code === 200) {
        const resData = res.data ? this.removeEmptyChildren(res.data) : [];
        this.setData({
          DeptTree: resData,
          DeptTreeShow: resData,
        })
      }
    })
  },
  GetCurrentWeather() {
    http.GetCurrentWeather().then(res => {
      if (res.code === 200) {
        this.setData({
          WeatherInfo: res.data
        });
        this.setSendInfo();
      }
    })
  },
  removeEmptyChildren(data) {
    data.forEach(item => {
      if (item.Children) {
        if (item.Children.length === 0) {
          delete item.Children; // 删除空Children字段
        } else {
          this.removeEmptyChildren(item.Children); // 递归处理非空Children
        }
      }
    });
    return data;
  },
  showPopup(e) {
    const popupType = e.currentTarget.dataset.pop;
    if (popupType === 'SubType' && this.data.submitData.ServiceType === '') {
      wx.showToast({
        title: '请先选择业务类型',
        icon: 'none'
      });
      return;
    }
    this.setData({
      [popupType + 'Show']: true
    });
  },
  closePop(e) {
    const popupType = e.currentTarget.dataset.pop;
    this.setData({
      [popupType + 'Show']: false
    });
    if (popupType === 'Dept') {
      this.setData({
        searchDeptTxt: '',
        DeptTreeShow: [...this.data.DeptTree]
      });
    }
  },
  UserSourceCancel() {
    this.setData({
      UserSourceShow: false
    });
  },
  UserSourceConfirm(e) {
    const {
      value,
      index
    } = e.detail;
    this.setData({
      'submitData.UserSourceName': value.name,
      'submitData.UserSource': value.value,
      UserSourceShow: false,
      UserSourceActive: index
    });
  },
  ServiceTypeCancel() {
    this.setData({
      ServiceTypeShow: false
    });
  },
  ServiceTypeConfirm(e) {
    const {
      value,
      index
    } = e.detail;
    this.setData({
      'submitData.ServiceTypeName': value.OrderTypeName,
      'submitData.ServiceType': value.OrderTypeNo,
      ServiceTypeShow: false,
      ServiceTypeActive: index,
    });

    const res = this.data.ServiceTypeList.find(item => {
      return item.OrderTypeNo === value.OrderTypeNo
    })
    if (res) {
      const SubTypeList = res.ChildNodeList;
      const SubTypeName = SubTypeList[0].OrderTypeName;
      const SubType = SubTypeList[0].OrderTypeNo;
      const NeedFile = SubTypeList[0].NeedFile;
      this.setData({
        SubTypeList: res.ChildNodeList,
        'submitData.SubTypeName': SubTypeName,
        'submitData.SubType': SubType,
        SubTypeActive: 0,
        NeedFile
      });
      this.setUrgencyAndTimeLimit(SubTypeList[0]);
    }
    this.setSendInfo();
  },
  SubTypeCancel() {
    this.setData({
      SubTypeShow: false
    });
  },
  SubTypeConfirm(e) {
    const {
      value,
      index
    } = e.detail;
    this.setData({
      'submitData.SubTypeName': value.OrderTypeName,
      'submitData.SubType': value.OrderTypeNo,
      SubTypeShow: false,
      SubTypeActive: index,
      NeedFile: value.NeedFile
    });
    this.setUrgencyAndTimeLimit(this.data.SubTypeList[index]);
  },
  setUrgencyAndTimeLimit(data) {
    console.log(data)
    if (data.UrgencyID && data.UrgencyID != '') {
      const index = this.data.UrgencyList.findIndex(item => item.UrgencyID === data.UrgencyID)
      this.setData({
        'submitData.UrgencyName': data.UrgencyName,
        'submitData.UrgencyID': data.UrgencyID,
        UrgencyActive: index
      });
    }
    if (data.TimeLimit && data.TimeLimit != '') {
      const index = this.data.TimeLimitList.findIndex(item => item.value === data.TimeLimit)
      this.setData({
        'submitData.TimeLimit': data.TimeLimit,
        'submitData.TimeLimitName': data.TimeLimitStr,
        TimeLimitActive: index
      });
    }
  },
  UrgencyCancel() {
    this.setData({
      UrgencyShow: false
    });
  },
  UrgencyConfirm(e) {
    const {
      value,
      index
    } = e.detail;
    this.setData({
      'submitData.UrgencyName': value.UrgencyName,
      'submitData.UrgencyID': value.UrgencyID,
      UrgencyShow: false,
      UrgencyActive: index
    });
  },
  TimeLimitCancel() {
    this.setData({
      TimeLimitShow: false
    });
  },
  TimeLimitConfirm(e) {
    const {
      value,
      index
    } = e.detail;
    this.setData({
      'submitData.TimeLimit': value.value,
      'submitData.TimeLimitName': value.showName,
      TimeLimitShow: false,
      TimeLimitActive: index
    });
  },
  DeptClose() {
    this.setData({
      DeptShow: false,
      searchDeptTxt: '',
      DeptTreeShow: [...this.data.DeptTree]
    });
  },
  DeptChange(e) {
    this.setData({
      placeholder: '请选择楼栋'
    });
  },
  DeptFinish(e) {
    const {
      selectedOptions,
      value
    } = e.detail;
    // const DeptName = selectedOptions
    //   .map((option) => option.NodeName)
    //   .join('/');
    const deptName = selectedOptions[0].NodeName;
    const buildingName = selectedOptions[1].NodeName;
    this.setData({
      DeptShow: false,
      'submitData.DeptName': deptName,
      'submitData.buildingName': buildingName,
      'submitData.DeptNo': value,
      searchDeptTxt: '',
      DeptTreeShow: [...this.data.DeptTree]
    });
    // this.setOrderAddress();
  },
  deptChange: tool.debounce(function (e) {
    const ev = e[0];
    const type = ev.currentTarget.dataset.type;
    this.setData({
      ['submitData.' + type]: ev.detail.value,
    });
    // this.setOrderAddress();
    this.getCConsInfo();
  }, 1000),
  SearchTypeChange(e) {
    this.setData({
      SearchType: e.detail.value
    });
  },
  inputChange(e) {
    const type = e.currentTarget.dataset.type;
    let val = e.detail.value;
    this.setData({
      ['submitData.' + type]: val
    });
  },
  meterChange: tool.debounce(function (e) {
    const ev = e[0];
    this.setData({
      'submitData.Meter_No': ev.detail.value,
    });
    this.getCConsInfo();
  }, 600),
  searchDeptChange: tool.debounce(function (e) {
    const ev = e[0];
    const val = ev.detail.value;
    const list = this.data.DeptTree.filter(item => item.NodeName.indexOf(val) > -1);
    this.setData({
      DeptTreeShow: list,
      'submitData.DeptName': '',
      'submitData.buildingName': '',
      'submitData.DeptNo': '',
      placeholder: '请选择'
    });
    // const cascader = this.selectComponent('.cus-cascader');
    // cascader && cascader.updateItems();
  }, 600),
  getCConsInfo() {
    const params = {
      queryParam: {}
    }
    if (this.data.SearchType === '1') {
      // params.queryParam.MeterNo = this.data.submitData.Meter_No;
      params.queryParam.CONS_NO = this.data.submitData.Meter_No;
    } else {
      params.queryParam.Area_Code_Building = this.data.submitData.DeptNo;
      params.queryParam.Room = this.data.submitData.Room;
      params.queryParam.Area_Code_Unit = this.data.submitData.Unit;
    }
    http.GetList_CC(params).then(res => {
      if (res.code === 200) {
        if (res.data.length === 0 || res.data.length > 1) {
          wx.showToast({
            title: '请完善条件后重新查询！',
            icon: 'none',
            duration: 2000
          })
        } else {
          if (this.data.SearchType === '1') {
            this.setData({
              'submitData.CONS_NAME_Search_1': res.data[0].CONS_NAME,
              'submitData.CONS_NO_Search_1': res.data[0].CONS_NO,
              'submitData.Address_Search_1': res.data[0].WATER_ADDR
            });
          } else {
            this.setData({
              'submitData.CONS_NAME_Search_2': res.data[0].CONS_NAME,
              'submitData.CONS_NO_Search_2': res.data[0].CONS_NO,
              'submitData.Address_Search_2': res.data[0].WATER_ADDR
            });
          }
          this.setSendInfo();
        }
      }
    })
  },
  // setOrderAddress() {
  //   let str = '';
  //   if (this.data.submitData.DeptName && this.data.submitData.DeptName != '') {
  //     str += this.data.submitData.DeptName;
  //   }
  //   if (this.data.submitData.buildingName && this.data.submitData.buildingName != '') {
  //     str += this.data.submitData.buildingName + '栋';
  //   }
  //   if (this.data.submitData.Unit && this.data.submitData.Unit != '') {
  //     str += this.data.submitData.Unit + '单元';
  //   }
  //   if (this.data.submitData.Room && this.data.submitData.Room != '') {
  //     str += this.data.submitData.Unit + '室';
  //   }
  //   this.setData({
  //     'submitData.Address': str
  //   })
  //   this.setSendInfo();
  // },
  leave() {
    this.setData({
      zpShow: false,
    });
  },
  /********** 转派相关 *********/
  handleSelect(e) {
    if (e.detail.tips) {
      console.log('必须选择到最末级节点');
    } else {
      this.setData({
        DEPT_NO: e.detail.item.DEPT_NO,
        AssignDeptNo: e.detail.item.P_DEPT_NO,
        HandleUserNo: e.detail.item.ABBR,
        Select_DEPT_NAME: e.detail.item.NAME
      });
    }
  },
  zpCancel() {
    this.setData({
      zpShow: false,
      DEPT_NO: '',
      Select_DEPT_NAME: ''
    });
  },
  zpConfirm() {
    this.setData({
      zpShow: false,
      'submitData.AssignDeptNo': this.data.AssignDeptNo,
      "submitData.HandleUserNo": this.data.HandleUserNo,
      "submitData.ZpName": this.data.Select_DEPT_NAME

    });
  },
  /********** 转派相关 *********/

  /*********************日期选择************* */
  changeBeginTime: function (e) {
    this.setData({
      "submitData.AppointmentBeginTime": e.detail.currentDateTimeStr
    });
  },
  changeEndTime: function (e) {
    this.setData({
      "submitData.AppointmentEndTime": e.detail.currentDateTimeStr
    });
  },
  /*********************日期选择************* */
  ResultRadioChange(e) {
    this.setData({
      'submitData.Status': e.detail.value
    })
  },
  setSendInfo() {
    this.setData({
      sendInfo: {
        WeatherInfo: this.data.WeatherInfo,
        // DeptName: this.data.userinfo.DEPT_NAME,
        // ConsName: this.data.userinfo.USER_NAME,
        Address: this.data.SearchType === '1' ? this.data.submitData.Address_Search_1 : this.data.submitData.Address_Search_2,
        NeedFile: this.data.NeedFile
      }
    });
  },
  Cancel() {
    wx.navigateBack();
  },
  toSubmit() {
    if (this.data.submitData.Status == '01') {
      // 转派
      this.DoDispatch();
    } else {
      // 直接处理
      this.DoHandle();
    }
  },
  Validate() {
    if (this.data.submitData.UserSourceName == null || this.data.submitData.UserSourceName === '') {
      wx.showToast({
        title: '客户来源不能为空！',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (this.data.submitData.PhoneNumber == null || this.data.submitData.PhoneNumber === '') {
      wx.showToast({
        title: '来电号码不能为空！',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (this.data.submitData.ServiceType == null || this.data.submitData.ServiceType === '') {
      wx.showToast({
        title: '业务类型不能为空！',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (this.data.submitData.SubType == null || this.data.submitData.SubType === '') {
      wx.showToast({
        title: '明细类型不能为空！',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (this.data.submitData.Description == null || this.data.submitData.Description === '') {
      wx.showToast({
        title: '工单描述不能为空！',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (this.data.submitData.Status === '01' && this.data.submitData.HandleUserNo == '') {
      wx.showToast({
        title: '请选择转派人员！',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (this.data.SearchType === '1' && (this.data.submitData.CONS_NO_Search_1 == null || this.data.submitData.CONS_NO_Search_1 === '')) {
      wx.showToast({
        title: '请查询用户！',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (this.data.SearchType === '2' && (this.data.submitData.CONS_NO_Search_2 == null || this.data.submitData.CONS_NO_Search_2 === '')) {
      wx.showToast({
        title: '请查询用户！',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (this.data.submitData.AppointmentBeginTime != '' && this.data.submitData.AppointmentEndTime != '') {
      if (new Date(this.data.submitData.AppointmentBeginTime).getTime() > new Date(this.data.submitData.AppointmentEndTime).getTime()) {
        wx.showToast({
          title: '预约结束时间不能小于预约开始时间！',
          icon: 'none',
          duration: 2000
        });
        return false;
      }
    }
    return true;
  },
  getSubmitData() {
    const AssignDeptNo = this.data.submitData.Status == '02' ? this.data.userinfo.DEPT_NO : this.data.submitData.AssignDeptNo;
    const HandleUserNo = this.data.submitData.Status == '02' ? this.data.userinfo.USER_NO : this.data.submitData.HandleUserNo;
    const params = {
      Status: this.data.submitData.Status,
      AddParam: {
        ConsNo: this.data.SearchType === '1' ? this.data.submitData.CONS_NO_Search_1 : this.data.submitData.CONS_NO_Search_2,
        SourceType: this.data.submitData.UserSource,
        PhoneNumber: this.data.submitData.PhoneNumber,
        // CONS_NAME_1: this.data.submitData.CONS_NAME_1,
        ServiceType: this.data.submitData.ServiceType,
        SubType: this.data.submitData.SubType,
        UrgencyID: this.data.submitData.UrgencyID,
        TimeLimit: this.data.submitData.TimeLimit,
        Description: this.data.submitData.Description,
        Address: this.data.submitData.Address,
        AppointmentBeginTime: this.data.submitData.AppointmentBeginTime,
        AppointmentEndTime: this.data.submitData.AppointmentEndTime,
        AssignDeptNo: AssignDeptNo,
        HandleUserNo: HandleUserNo,
        HandleWay: 1,
      },
      HandleParam: {
        ProcedureCode: this.data.submitData.Status == '01' ? '02' : '04',
        ProcedureStatus: 2,
        HandlerResult: this.data.submitData.HandlerResult,
        ProcHandResult: '1',
        AssignDeptNo: AssignDeptNo,
        HandleUserNo: HandleUserNo,
        FileList: [],
        HandleWay: 1
      }
    }
    return params;
  },
  DoDispatch() {
    const res = this.Validate();
    if (res) {
      wx.showModal({
        title: '提示',
        content: '确定要提交处理吗？',
        success: (res) => {
          if (res.confirm) {
            // const params = this.getSubmitData();
            this.DoSubmit(null, null);
          }
        }
      });
    }
  },
  DoHandle() {
    const _this = this;
    const res = _this.Validate();
    let returnData = {};
    const comp = _this.selectComponent('.templete-component');
    if (comp) {
      returnData = comp.getSubmitData();
    }
    if (res && returnData) {
      wx.showModal({
        title: '提示',
        content: '确定要提交处理吗？',
        success(res) {
          if (res.confirm) {
            const compUpload = _this.selectComponent('.upload-component');
            const uploadData = compUpload.getSubmitData();
            const files = uploadData.files;
            const allUpload = uploadData.allUpload;
            // const params = _this.getSubmitData();
            // params.HandleParam.FileList = uploadData.files;
            if (_this.data.NeedFile === 1 && files.length === 0) {
              wx.showToast({
                title: '请先上传图片、视频或录音！',
                icon: 'none',
                duration: 2000
              });
              return;
            }
            if (!allUpload) {
              wx.showModal({
                content: '你有未上传的录音，是否继续上传？',
                cancelText: '否',
                confirmText: '是',
                success: (res) => {
                  if (res.confirm) {
                    return;
                  } else if (res.cancel) {
                    // params.HandleParam = {
                    //   ...params.HandleParam,
                    //   ...returnData
                    // }
                    _this.DoSubmit(returnData, files);
                  }
                }
              })
            } else {
              // params.HandleParam = {
              //   ...params.HandleParam,
              //   ...returnData
              // }
              _this.DoSubmit(returnData, files);
            }
          }
        }
      });
    }
  },
  DoSubmit(returnData, files) {
    const params = this.getSubmitData();
    if (files) {
      params.HandleParam.FileList = files;
    }
    if (returnData) {
      params.HandleParam = {
        ...params.HandleParam,
        ...returnData
      }
    }
    wx.showLoading({
      mask: true,
      title: '提交处理中...'
    });
    http.RegisterConsOrder(params).then(res => {
      if (res.code === 200) {
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 2000,
          success: function () {
            setTimeout(() => {
              wx.navigateBack();
            }, 2000)
          }
        })
      } else {
        wx.showToast({
          title: res.info,
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
})